package com.example.costumview.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.costumview.R;

public class EraserView_SRCOUT2 extends View {

    private Paint mBitPaint;
    private Bitmap mBmpDST, mBmpSRC,mBmpText;
    private Path mPath;
    private float mPreX, mPreY;

    public EraserView_SRCOUT2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mBitPaint = new Paint();
        mBitPaint.setColor(Color.RED);
        mBitPaint.setStyle(Paint.Style.STROKE);
        mBitPaint.setStrokeWidth(45);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;

        mBmpText=BitmapFactory.decodeResource(getResources(),R.drawable.thankyou,null);
        mBmpSRC = BitmapFactory.decodeResource(getResources(), R.drawable.dog, options);
        mBmpDST = Bitmap.createBitmap(mBmpSRC.getWidth(), mBmpSRC.getHeight(), Bitmap.Config.ARGB_8888);
        mPath = new Path();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                mPreX = event.getX();
                mPreY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                float endX = (mPreX + event.getX()) / 2;
                float endY = (mPreY + event.getY()) / 2;

                mPath.quadTo(mPreX, mPreY, endX, endY);
                mPreX = event.getX();
                mPreY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        postInvalidate();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //先画出底层的结果图片
        canvas.drawBitmap(mBmpText,null,new RectF(0,0,mBmpDST.getWidth(),mBmpDST.getHeight()),mBitPaint);

        int layerId=canvas.saveLayer(0,0,getWidth(),getHeight(),null,Canvas.ALL_SAVE_FLAG);

        //再把手势轨迹画在目标图像上
        Canvas c=new Canvas(mBmpDST);
        c.drawPath(mPath,mBitPaint);

        //然后把目标图片画到画布上
        canvas.drawBitmap(mBmpDST,0,0,mBitPaint);

        //计算源图像区域
        mBitPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
        canvas.drawBitmap(mBmpSRC,0,0,mBitPaint);

        mBitPaint.setXfermode(null);
        canvas.restoreToCount(layerId);
    }
}
